package com.campus.commons.utils.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云 OSS文件类
 */
public class AliOssCloudUtil {

    //bucket所在地
    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    //RAM 的 accessKeyId
    private static String accessKeyId = "LTAI4GFTUeWLR5e3uU5RHBFp";
    //RAM 的 accessKeySecret
    private static String accessKeySecret = "0fUS8kOt14UXTXgR1TXwAGtp0oRXtX";
    //空间
    private static String bucketName = "yhll";
    private static String index_image = "home-images";
    //文件存储目录
    private static String filedir = "test/";

    private static OSSClient ossClient;

//    static {
//        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//    }
public static void InitOss() {
    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
    public String getFiledir() {
        return this.filedir;
    }

    //自定义上传文件夹
    public AliOssCloudUtil(String filedir) {
        this.filedir = filedir;
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }


    /**
     * 初始化
     */
    public static void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }


    /**
     * 刪除文件方法
     *
     * @param remoteFileName 要删除的文件相对bucketName的路径
     * @return 成功返回true
     */
    public static Boolean deleteFile(String remoteFileName) {
        InitOss();
        try {
            ossClient.deleteObject(bucketName, filedir + remoteFileName);
            System.out.println(bucketName+"/"+remoteFileName);
            boolean exist = doesObjectExist(filedir+remoteFileName);
            if (!exist) {
                return true;
            }
            return false;
        } finally {
            ossClient.shutdown();

        }
    }

    /**
     * 上传到OSS服务器
     * 第一个参数为文件路径，第二个为文件名称 ，第三个是否开启读条
     *
     * @param instream      文件流
     * @param StartProgress 是否开启进度条
     * @param fileName      文件名称 包括后缀名
     * @param StartProgress 是否开启上传条
     * @return map
     * key :url
     * key:fileRelativePath
     */
    public static Map<String, String> uploadFile2OSS(String instream, String fileName, Boolean StartProgress) {
        InitOss();
        Map<String, String> map = null;
        String ret = "";
        // 判断bucket是否已经存在,不存在进行创建
        if (!doesBucketExist()) {
            createBucket();
        }
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
            String objectName = filedir + fileName;
            //判断是否开启读条
            if (StartProgress) {
                ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File(instream)).
                        <PutObjectRequest>withProgressListener(new PutObjectListener()));
            } else {
                FileInputStream inputStream = new FileInputStream(new File(instream));
                ossClient.putObject(bucketName, objectName, inputStream);
            }
            // url拼接 这里是我们要下载的连接地址
            String url = "http://" + bucketName + "." + endpoint + "/" + objectName;
            String fileRelativePath = bucketName + "/" + objectName;
            ret = url;
            map = new HashMap<String, String>();
            //存入url http
            map.put("url", ret);
            //相对于oss的路径
            map.put("fileRelativePath", fileRelativePath);
        } catch (Exception e) {

        } finally {
            ossClient.shutdown();
        }
        return map;
    }

    /**
     * 上传文件
     * @param fileName
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static Map<String,String> uploadFIle(String fileName,InputStream file) throws FileNotFoundException {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
        PutObjectResult result = ossClient.putObject(index_image, fileName, file);

// 关闭OSSClient。
        ossClient.shutdown();
        Map<String, String> map = new HashMap<>();
        map.put("url", "http://" + index_image + "." + endpoint + "/" + fileName);
        map.put("fileRelativePath", index_image + "/" + fileName);
        return map;

    }

    /**
     * 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS，
     * 如果为true则忽略302重定向或镜像；如果为false，则考虑302重定向或镜像。
     * yourObjectName 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     *
     * @return 存在返回true
     */
    public static boolean doesObjectExist(String objectName) {
        InitOss();
        boolean exists = ossClient.doesObjectExist(bucketName, objectName);
        ossClient.shutdown();
        return exists;
    }


    /**
     * 判断Bucket是否存在
     *
     * @return 存在返回true
     */
    public static boolean doesBucketExist() {
        InitOss();
        boolean exists = ossClient.doesBucketExist(bucketName);
        return exists;
    }

    /**
     * 创建Bucket
     */
    public static void createBucket() {
        InitOss();
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置bucket权限为公共读，默认是私有读写
        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
        // 设置bucket存储类型为低频访问类型，默认是标准类型
        createBucketRequest.setStorageClass(StorageClass.IA);
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            try {
                ossClient.createBucket(createBucketRequest);
                // 关闭client
                ossClient.shutdown();
            } catch (Exception e) {

            }
        }
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if ("bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
                "jpg".equalsIgnoreCase(FilenameExtension) ||
                "png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(FilenameExtension) ||
                "ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(FilenameExtension) ||
                "doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpeg";
    }


    /**
     * @param fileName
     * @return
     * @Title: getInputStreamByFileUrl
     * @Description: 根据文件路径获取InputStream流
     * @return: InputStream
     */
    public InputStream getInputStreamByFileUrl(String fileName) {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        return ossObject.getObjectContent();
    }


    public static File getExcelFileByHTTP(String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        File file = new File(new File("").getAbsolutePath() + "/" + fileName);
        ossClient.getObject(new GetObjectRequest(bucketName, filedir + fileName), file);
        // 关闭OSSClient。
        ossClient.shutdown();
        return file;

    }


    public static void main(String[] args) {
//        Map<String, String> map = AliOssCloudUtil.uploadFile2OSS("C:\\Users\\33325\\Desktop\\管理系统开发文件\\可行性报告.docx", "可行性报告.docx", true);
//        System.out.println();

        Boolean aBoolean = AliOssCloudUtil.deleteFile("新建文本文档.txt");
        System.out.println(aBoolean);

    }
}